package com.linxcool.media;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.linxcool.util.R;

public class ImageGridAdapter extends ImageBucketAdapter{

	List<ImageItem> dataList;

	@SuppressWarnings("unchecked")
	public ImageGridAdapter(Context context, List<?> dataList) {
		super(context, null);
		this.dataList = (List<ImageItem>) dataList;
	}

	@Override
	public int getCount() {
		return dataList.size();
	}

	@Override
	public Object getItem(int position) {
		return dataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			GHolder holder = new GHolder();

			convertView = View.inflate(context, R.layout.item_photos, null);
			
			holder.iv = (ImageView) convertView.findViewById(R.id.image);
			holder.selected = (ImageView) convertView.findViewById(R.id.isselected);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			convertView.setTag(holder);

			setItem(holder,(ImageItem)getItem(position),position);
		} 
		else {
			setVisibleItemCount(convertView);
			GHolder holder = (GHolder) convertView.getTag();
			setItem(holder,(ImageItem)getItem(position),position);
		}

		return convertView;
	}

	protected void setItem(GHolder holder,ImageItem item,int position){
		if (item.isSelected){
			holder.selected.setImageResource(R.drawable.ic_selected);
			holder.name.setBackgroundResource(R.drawable.bgd_relatly_line);
		}
		else{
			holder.selected.setImageDrawable(null);
			holder.name.setBackgroundColor(0x00000000);
		}
		item.arg1 = position;
		holder.iv.setTag(item);
		holder.iv.setOnClickListener(holder);
		displayBitmap(holder.iv, item);
	}
	
	public class GHolder extends Holder implements OnClickListener{
		@Override
		public void onClick(View v) {
			ImageItem item = (ImageItem) v.getTag();
			item.isSelected = !item.isSelected;
			if (item.isSelected) {
				selected.setImageResource(R.drawable.ic_selected);
				name.setBackgroundResource(R.drawable.bgd_relatly_line);
			} 
			else if (!item.isSelected) {
				selected.setImageDrawable(null);
				name.setBackgroundColor(0x00000000);
			}
		}
	}

}
